export default {
	namespaced: true,
	state: () => ({
		//goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		addtoCart(state, goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
			if (!findResult) {
				state.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			this.commit('moduleCart/saveToStorage')
		},

		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},

		updateRadioChange(state, goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_state = goods.goods_state
				this.commit('moduleCart/saveToStorage')
			}
		},

		updateNumCount(state, goods) {
			const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findResult) {
				findResult.goods_count = goods.goods_count
				this.commit('moduleCart/saveToStorage')
			}
		},

		deleteGoodItem(state, goods_id) {
			state.cart = state.cart.filter(item => item.goods_id !== goods_id)
			this.commit('moduleCart/saveToStorage')
		},

		updateAllChecked(state, goods_state) {
			state.cart.forEach(item => item.goods_state = goods_state)
			this.commit('moduleCart/saveToStorage')
		}
	},
	getters: {
		total(state) {
			return state.cart.reduce((total, item) => total += item.goods_count, 0)
		},

		checkedCount(state) {
			return state.cart.filter(item => item.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},

		totalPrice(state) {
			return state.cart.filter(item => item.goods_state)
				.reduce((total, item) => total += item.goods_price*item.goods_count, 0)
				.toFixed(2)
		}
	}
}
